package com.example.design.函数式编程.f高阶函数;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 高阶函数：filter,map,flatMap
 */
public class FilterDemo {
    public static void main(String[] args) {
        List<Fruit> fruitList = new ArrayList<>();
        fruitList.add(new Fruit("pg", "red"));
        fruitList.add(new Fruit("jg", "purse"));
        fruitList.add(new Fruit("lz", "yellow"));

        // 过滤
        List<Fruit> res = fruitList.stream().filter(item -> item.color.equals("red")).collect(Collectors.toList());
        System.out.println(res);

        // 映射
        List<String> colors = fruitList.stream().map(Fruit::getColor).collect(Collectors.toList());
        System.out.println(colors);

        // 扁平化映射。可以将流中的每个元素转换为一个新的流，还可以将多个流合并成一个单一的流。
        List<List<Fruit>> nestedList = Arrays.asList(
                Arrays.asList(new Fruit("pg", "red"), new Fruit("jg", "purse")),
                Arrays.asList(new Fruit("lz", "yellow")),
                Arrays.asList(new Fruit("pt", "black"))
        );
        // 从nestedList获取所有颜色
        List<String> flatMapColors = nestedList.stream().flatMap(item -> item.stream().map(Fruit::getColor)).collect(Collectors.toList());
        System.out.println();
    }
}
